package com.bezdelnick.forum.web.page;

import com.bezdelnick.forum.domain.Answer;
import com.bezdelnick.forum.domain.Question;
import com.bezdelnick.forum.mail.MailFactory;
import com.bezdelnick.forum.mail.type.AbstractMail;
import com.bezdelnick.forum.service.ForumService;
import com.bezdelnick.forum.web.model.AddingAnswer;
import com.bezdelnick.forum.web.page.template.UserMainMenuTemplate;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: User
 * Date: 10.08.12
 * Time: 14:12
 * To change this template use File | Settings | File Templates.
 */
@AuthorizeInstantiation("ROLE_USER")
public class AddAnswerPage extends UserMainMenuTemplate {
    private static final Logger LOGGER = LoggerFactory.getLogger(AddAnswerPage.class);

//    @SpringBean
//    @SuppressWarnings("unused")
//    MailSendManager mailSendManager;

    @SpringBean
    @SuppressWarnings("unused")
    public ForumService forumService;

    private PageParameters parameters;

    public AddAnswerPage(PageParameters parameters) {
        this.parameters = parameters;

        // add menu component
        //add(new Label("menu", "This is menu! =)"));

        // add body component
        AddAnswerForm form = new AddAnswerForm("form");
        add(form);
    }

    private class AddAnswerForm extends Form<AddingAnswer> {
        private static final long serialVersionUID = 1L;

        Label lblAuthorQuestion;
        Label lblTitleQuestion;
        Label lblTextQuestion;
        FormComponent<String> taTextAnswer;

        private Question question;

        public AddAnswerForm(String id) {
            super(id);
            setModel(new CompoundPropertyModel<AddingAnswer>(new AddingAnswer()));
        }

        @Override
        protected void onInitialize() {
            super.onInitialize();

            question = forumService.getQuestionDao().getQuestionById(
                    parameters.get("id").toLong()
            );

            lblAuthorQuestion = new Label("author", forumService.getAppUserDao().getUserById(question.getUserId()).getUsername());
            lblTitleQuestion = new Label("title", question.getTitle());
            lblTextQuestion = new Label("text", question.getTextQuestion());
            taTextAnswer = new TextArea("answer").setRequired(true);

            add(lblAuthorQuestion);
            add(lblTitleQuestion);
            add(lblTextQuestion);
            add(taTextAnswer);
        }

        @Override
        protected void onSubmit() {
            AddingAnswer addingAnswer = getModelObject();

            Answer answer = new Answer();
            answer.setTextAnswer(HtmlUtils.htmlUnescape(addingAnswer.getAnswer()));
            answer.setDatePublication(new Date());
            answer.setQuestionId(question.getId());
            answer.setRating(0);
            answer.setUserId(forumService.getCurrentUser().getId());

            if (true) {
                // Send mail
                AbstractMail addAnswerMail = MailFactory.buildMailFor(Answer.class);
                addAnswerMail.setSubject("Programmers forum. You have got a new answer.");
                addAnswerMail.setRecipients(new String[]{
                        forumService.getAppUserDao().getUserById(
                                question.getUserId()
                        ).getEmail()
                });
                addAnswerMail.setSender("gofor.broake665@gmail.com");

                if (addAnswerMail.buildContext(answer)) {
                    forumService.getMailSendManager().sendMessage(addAnswerMail);
                }

                // Write data to database
                forumService.getAnswerDao().insertAnswer(answer);
            }

            setModelObject(new AddingAnswer());

            PageParameters parameters = new PageParameters();
            parameters.add("id", question.getId());
            ShowQuestionPage showQuestionPage = new ShowQuestionPage(parameters);
            redirectToInterceptPage(showQuestionPage);
        }
    }
}
